<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, getCurrentInstance } from 'vue'
	import { useUserStore } from '@/store/user'
	import { searchKitchen, consultKitchen } from '@/api/shop'
	import { getAddressAfter } from '@/api/login'
	import { parseTime } from '@/utils/common'
	const instance = getCurrentInstance().proxy
	
	const user = useUserStore()
	const config = getApp().globalData.config
	const loading = ref(false)
	const loadStatus = ref('loadmore')
	const sortPicker = ref(null)
	const sortColumns = [{label: '星级从高到低', value: 3}, {label: '接单量从高到低', value: 1}]
	const treePopup = ref(null)
	const selectOrg = ref({label: '', value: ''})
	const orgTree = ref([])
	const query = ref({chefName: '', conditions: '', areaId: user.addressIds[2], current: 1, size: 20})
	const triggered = ref(false)
	const total = ref(0)
	const list = ref([])
	const shadowStyle = {
		position: 'absolute',
		bottom: 0,
		right: 0,
		width: '84rpx',
		backgroundImage: "linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, #fff 30%)"
	}
	const type = ref('view')
	const selectId = ref(null)
	
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		triggered.value = true
		list.value = []
		query.value.current = 1
		searchKitchen(query.value).then(res => {
			let result = res.result || {}
			let data = result.records || []
			total.value = Number(result.total)
			list.value = data
			triggered.value = false
			let curLength = list.value.length || 0
			loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
		}).catch(() => {
			triggered.value = false
			loadStatus.value = 'loadmore'
		})
	}
	function lowerList() {
		if(list.value.length < total.value){
			loadStatus.value = 'loading'
			query.value.current ++
			searchKitchen(query.value).then(res => {
				let result = res.result || {}
				let data = result.records || []
				total.value = Number(result.total)
				list.value.push(...data)
				let curLength = list.value.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function selectChef(item) {
		if(type.value === 'select') {
			selectId.value = item.chefId
			setTimeout(() => {
				uni.navigateBack({
					success: () => {
						const eventChannel = instance.getOpenerEventChannel()
						eventChannel.emit('selectKitchen', uni.$uv.deepClone(item))
					}
				})
			}, 200)
		}
		// let url = `/pages/shop/kitchenDetail?id=${item.chefId}`
		// uni.navigateTo({url})
	}
	function search() {
		triggered.value = true
	}
	function getLevelImg(value) {
		switch(value) {
			case 1: return 'https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-05-12/1747014216341_level_1.png';
			case 2: return 'https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-05-12/1747014219065_level_2.png';
			case 3: return 'https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-05-12/1747014221975_level_3.png';
			case 4: return 'https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-05-12/1747014225179_level_4.png';
			case 5: return 'https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-05-12/1747014228543_level_5.png';
			default: return ''
		}
	}
	function getLevelText(value) {
		switch(value) {
			case 1: return '一星级';
			case 2: return '二星级';
			case 3: return '三星级';
			case 4: return '四星级';
			case 5: return '五星级';
			default: return ''
		}
	}
	function clearParams(name) {
		if(name === 'areaId') {
			selectOrg.value = {label: '', value: ''}
			query.value.areaId = user.addressIds[2]
		} else {
			query.value[name] = ''
		}
		triggered.value = true
	}
	function sortConfirm(e) {
		let item = e.value[0]
		query.value.conditions = item.value
		triggered.value = true
	}
	function getSortStatus(value) {
		let cur = sortColumns.find(item => item.value === value)
		if(cur) return cur.label
		else return ''
	}
	function initArea() {
		getAddressAfter(user.addressIds[2]).then(res => {
			let data = res.result || []
			orgTree.value = initTreeData(data)
		})
	}
	function initTreeData(data = []) {
		let arr = []
		data.forEach(item => {
			let newItem  = {
				label: item.areaName,
				value: item.areaId,
				expand: false
			}
			if(item.children && item.children.length) newItem.children = initTreeData(item.children)
			arr.push(newItem)
		})
		return arr
	}
	function cancelTree() {
		treePopup.value.close()
	}
	function orgConfirm() {
		cancelTree()
		if(selectOrg.value.value) {
			query.value.areaId = selectOrg.value.value
			triggered.value = true
		}
	}
	function orgClick(item) {
		selectOrg.value = item
	}
	function orgExpand(item) {
		let curItem = treeFind(orgTree.value, item.value)
		if(curItem) curItem.expand = !curItem.expand
	}
	function treeFind(data = [], value) {
		let findItem = null
		for(let i = 0; i < data.length; i++) {
			let item = data[i]
			if(item.value === value) {
				findItem = item
				break
			} else if(item.children) {
				findItem = treeFind(item.children, value)
				if(findItem) break
			}
		}
		return findItem
	}
	function nowConsult(item) {
		loading.value = true
		consultKitchen({chefId: item.chefId, chefName: item.chefName}).then(res => {
			loading.value = false
			uni.navigateTo({url: '/pages/shop/kitchenSuccess'})
		}).catch(() => loading.value = false)
	}
	
	onLoad((option) => {
		type.value = option.type || 'view'
		if(option.chefId) {
			selectId.value = Number(option.chefId || 0)
		}
		if(option.chefName) {
			query.value.chefName = option.chefName
		}
		search()
		initArea()
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head">
			<view class="search-box theme-btn">
				<uv-icon name="search" color="#5B5B5B" size="50" />
				<input type="text" focus v-model="query.chefName" placeholder="搜索您需要的厨师" class='input-text' confirm-type="search" @confirm="search" />
				<uv-button color="linear-gradient(245deg, #F92E1D 0%, #FF3E49 100%)" :custom-style="{height: '56rpx'}" shape="circle" size="small" text="搜索"
					:disabled="loading" @click="search" />
			</view>
			<view class="query-box">
				<view class="query-item" @click="treePopup.open()">
					<text class="uv-line-1">{{selectOrg.label || '乡镇筛选'}}</text>
					<view v-if="selectOrg.label !== ''" @click.stop="clearParams('areaId')">
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
				<view class="query-item" @click="sortPicker.open()">
					<text class="uv-line-1">{{getSortStatus(query.conditions) || '排序筛选'}}</text>
					<view v-if="query.conditions !== ''" @click.stop="clearParams('conditions')">
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
			</view>
		</view>
		<scroll-view scroll-y="true" class="app-content" refresher-enabled :refresher-triggered="triggered" @refresherrefresh="refreshList" lower-threshold="10" @scrolltolower="lowerList">
			<view class="content-list" v-if="list.length">
				<view v-for="(item, index) in list" :key="item.chefId" :class="['kitchen-box', selectId == item.chefId? 'active' : '']" @click="selectChef(item)">
					<view class="kitchen-index">{{index + 1}}</view>
					<view class="kitchen-main">
						<view class="kitchen-img">
							<uv-image :src="item.avatars && item.avatars[0] && item.avatars[0].furl" width="128" height="128" shape="circle"></uv-image>
							<view :class="['level', 'level-' + item.applyChef.level]" v-if="item.applyChef">
								<image class="level-img" :src="getLevelImg(item.applyChef.level)" mode="aspectFill"></image>
								<text>{{getLevelText(item.applyChef.level)}}</text>
							</view>
						</view>
						<view class="kitchen-info">
							<view class="kitchen-top">
								<view class="kitchen-name uv-line-1">
									<text>{{item.chefName || '--'}}</text>
									<text class="kitchen-age" v-if="item.age">{{item.age}}岁</text>
								</view>
								<view class="kitchen-code">编号：{{item.code || '--'}}</view>
							</view>
							<view class="kitchen-address">{{item.areaName || '--'}}</view>
							<view class="kitchen-tags">
								<uv-tags v-for="(specialty, i) in item.specialtys" :key="i" :text="specialty" borderColor="rgba(250,63,0,0.1)" 
									bgColor="rgba(250,63,0,0.1)" color="#FA3F00" shape="circle" size="mini"></uv-tags>
							</view>
						</view>
					</view>
					<view class="kitchen-card">
						<view class="card-box">
							<image class="card-img" src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-13/1749786071602_kitchen-health.png" mode="aspectFill"></image>
							<text>健康证有效期至{{item.applyChef && parseTime(item.applyChef.healthTime, '{y}年{m}月{d}日') || '~'}}</text>
						</view>
						<view class="card-box certificate">
							<image class="card-img" src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-13/1749786074160_kitchen-certificate.png" mode="aspectFill"></image>
							<text>培训合格证处于有效期内</text>
						</view>
					</view>
					<view class="kitchen-des">
						<image class="des-img" src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-16/1750045188197_introduction.png" mode="aspectFill"></image>
						<view class="des-content content-text">工作年限{{item.workYear || '20'}}年，厨师{{getLevelText(item.applyChef && item.applyChef.level)}}</view>
					</view>
					<view class="kitchen-des">
						<image class="des-img" src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-16/1750045190693_excel.png" mode="aspectFill"></image>
						<view class="des-content">
							<uv-read-more show-height="80rpx" :toggle="true" closeText="" textIndent="0" fontSize="24rpx" color="#999999" :shadowStyle="shadowStyle">
								<view class="content-text">{{item.cuisine || '--'}}</view>
							</uv-read-more>
						</view>
					</view>
					<view class="kitchen-bottom theme-btn">
						<text class="bottom-num">已接单{{item.numbers || 0}}次</text>
						<uv-button color="#FA3F00" size="small" shape="circle" text="立即咨询" :disabled="loading" @click="nowConsult(item)"
							:custom-style="{width: '160rpx'}" v-if="type === 'view'"></uv-button>
					</view>
				</view>
				<uv-load-more :status="loadStatus" fontSize="28" iconSize="34" isDot line></uv-load-more>
			</view>
			<empty text="没有找到您搜索的厨师" v-else-if="loadStatus != 'loading'"></empty>
		</scroll-view>
		
		<uv-picker ref="sortPicker" title="排序筛选" :columns="[sortColumns]" keyName="label" visibleItemCount="8" @confirm="sortConfirm"></uv-picker>
		<uv-popup ref="treePopup" mode="bottom">
			<view class="tree-popup">
				<view class="popup-head">
					<text @click="cancelTree" class="btn">取消</text>
					<text class="text">乡镇筛选</text>
					<text @click="orgConfirm" class="btn primary">确定</text>
				</view>
				<scroll-view scroll-y="true" class="tree-scroll">
					<tree :data="orgTree" :value="selectOrg.value? selectOrg.value : 0" @clicKNode="orgClick" @changeExpand="orgExpand"></tree>
				</scroll-view>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		height: 100vh;
		padding-top: 2rpx;
		padding-bottom: 16rpx;
		.app-head{
			margin-bottom: 24rpx;
			height: 192rpx;
			background-color: #FFFFFF;
			padding-top: 16rpx;
			.search-box{
				margin: 0 16rpx 16rpx;
				height: 72rpx;
				padding: 8rpx;
				display: flex;
				align-items: center;
				gap: 6rpx;
				border: 2rpx solid #FE3B00;
				border-radius: 72rpx;
				background-color: #FFFFFF;
				.input-text{
					flex: 1;
				}
			}
			.query-box{
				height: 88rpx;
				background-color: #FFFFFF;
				display: flex;
				align-items: center;
				.query-item{
					width: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 8rpx;
					padding: 0 4rpx;
				}
			}
		}
		.app-content{
			height: calc(100% - 218rpx);
			.content-list{
				padding: 0 24rpx;
				display: flex;
				flex-direction: column;
				gap: 16rpx;
			}
			.kitchen-box{
				padding: 24rpx;
				border-radius: 12rpx;
				background-color: #FFFFFF;
				position: relative;
				.kitchen-index{
					position: absolute;
					top: 0;
					left: 8rpx;
					z-index: 1;
					width: 40rpx;
					height: 48rpx;
					line-height: 40rpx;
					text-align: center;
					font-size: var(--theme-sm);
					color: #FFFFFF;
					background: linear-gradient( 180deg, #FA3F00 0%, #FF8055 100%);
					clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 50% 85%, 0 100%);
					border-radius: 8rpx 8rpx 0 0;
				}
				.kitchen-main{
					display: flex;
					gap: 16rpx;
				}
				.kitchen-img{
					display: flex;
					flex-direction: column;
					margin-bottom: 16rpx;
					.level{
						margin-top: -24rpx;
						z-index: 1;
						padding: 6rpx 8rpx;
						display: flex;
						align-items: center;
						gap: 6rpx;
						border-radius: 24rpx;
						font-size: var(--theme-sm);
						line-height: var(--theme-sm-line);
						.level-img{
							width: 28rpx;
							height: 28rpx;
						}
					}
					.level-1{
						background: linear-gradient( 90deg, #F9B185 0%, #ECCFBD 74%);
						color: #A94E16;
					}
					.level-2{
						background: linear-gradient( 90deg, #85D0F9 0%, #B1E4FF 74%);
						color: #1676A9;
					}
					.level-3{
						background: linear-gradient( 90deg, #F9C585 0%, #ECD7BD 74%);
						color: #DB5319;
					}
					.level-4{
						background: linear-gradient( 90deg, #F985CD 0%, #FDB6E2 74%);
						color: #A91671;
					}
					.level-5{
						background: linear-gradient( 90deg, #A485F9 0%, #D3C3FF 74%);
						color: #3D16A9;
					}
				}
				.kitchen-info{
					width: calc(100% - 146rpx);
					.kitchen-top{
						margin-bottom: 8rpx;
						display: flex;
						align-items: center;
						gap: 6rpx;
						.kitchen-name{
							flex: 1;
							font-weight: 600;
							font-size: var(--theme-lg);
							line-height: var(--theme-lg-line);
							.kitchen-age{
								margin-left: 16rpx;
								font-weight: 400;
								font-size: var(--theme-sm);
								color: #656161;
							}
						}
						.kitchen-code{
							flex-shrink: 0;
							color: #999999;
							font-size: var(--theme-sm);
							line-height: var(--theme-sm-line);
						}
					}
					.kitchen-address{
						margin-bottom: 16rpx;
						color: #656161;
						font-size: var(--theme-sm);
						line-height: var(--theme-sm-line);
					}
					.kitchen-tags{
						min-height: 44rpx;
						display: flex;
						align-items: center;
						flex-wrap: wrap;
						gap: 12rpx;
					}
				}
				.kitchen-card{
					margin-bottom: 16rpx;
					display: flex;
					gap: 8rpx;
					font-size: var(--theme-xs);
					line-height: var(--theme-xs-line);
					.card-box{
						padding: 8rpx;
						background: #EBFFF3;
						border: 1rpx solid #5FD897;
						border-radius: 8rpx;
						display: flex;
						align-items: center;
						gap: 4rpx;
						&.certificate{
							background: #EBF7FF;
							border: 1rpx solid #63BFF9;
						}
						.card-img{
							width: 32rpx;
							height: 32rpx;
						}
					}
				}
				.kitchen-des{
					display: flex;
					gap: 12rpx;
					margin-bottom: 12rpx;
					.des-img{
						width: 56rpx;
						height: 40rpx;
					}
					.des-content{
						width: calc(100% - 68rpx);
					}
					.content-text{
						color: #656161;
						font-size: var(--theme-df);
						line-height: var(--theme-df-line);
					}
				}
				.kitchen-bottom{
					margin-top: 16rpx;
					display: flex;
					align-items: center;
					gap: 6rpx;
					.bottom-num{
						flex: 1;
						font-size: var(--theme-sm);
						line-height: var(--theme-sm-line);
						color: #999999;
					}
				}
				&.active{
					border: 2rpx solid #FD1024;
				}
			}
		}
		.tree-popup{
			.popup-head{
				display: flex;
				align-items: center;
				gap: 8rpx;
				padding: 16rpx 32rpx;
				.btn{
					flex-shrink: 0;
					width: 100rpx;
					color: #909193;
					&.primary{
						color: #FA3F00;
						text-align: right;
					}
				}
				.text{
					flex: 1;
					text-align: center;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line); 
				}
			}
			.tree-scroll{
				height: 400rpx;
				padding-top: 20rpx;
			}
		}
	}
</style>